package com.supersit.GZFDA.activity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.supersit.GZFDA.R;
import com.supersit.GZFDA.adapter.UnUpLoadDataAdatper;
import com.supersit.GZFDA.adapter.UnUpLoadDataAdatper.Callback;
import com.supersit.GZFDA.api.APIConstants;
import com.supersit.GZFDA.db.DBUtils;
import com.supersit.GZFDA.entity.Business;
import com.supersit.GZFDA.entity.UnUpLoad;
import com.supersit.GZFDA.util.AppManager;
import com.supersit.GZFDA.util.CustomMultipartEntity;
import com.supersit.GZFDA.util.CustomMultipartEntity.ProgressListener;
import com.supersit.GZFDA.util.HttpMultipartPost.GetResult;
import com.supersit.GZFDA.util.MyLog;
import com.supersit.GZFDA.util.NetUtils;
import com.supersit.GZFDA.util.ToURLEncode;

public class UpLoadActivity extends Activity implements Callback, GetResult {
	private final static String TAG = UpLoadActivity.class.getSimpleName();
	private List<UnUpLoad> upLoadDataList;
	private ListView listView;
	private UnUpLoadDataAdatper adapter;
	private ImageView ivChecked;
	private Context context;
	private ProgressDialog pd;
	private UnUpLoad u;
	private static int ImageUpSuccess = 1;
	private static int ImageUpFailure = -1;
	private int pos;
	public static Button btn_batch_upload;
	private TextView tv_back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		AppManager.getAppManager().addActivity(UpLoadActivity.this);
		context = this;
		listView = (ListView) findViewById(R.id.lv_unupload_data);
		upLoadDataList = DBUtils.getUnUpLoadData(context);

		tv_back = (TextView) findViewById(R.id.tv_back);
		ivChecked = (ImageView) findViewById(R.id.ib_batch);
		btn_batch_upload = (Button) findViewById(R.id.btn_batch_upload);
		btn_batch_upload.setVisibility(View.GONE);
		btn_batch_upload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int count = 0;
				List<UnUpLoad> list = adapter.getList();
				if (list.size() > 0) {
					for (UnUpLoad uu : list) {
						if (uu.isSelected()) {
							count++;
						}
					}
					if (count > 0) {
						if (NetUtils.isConnected(context)) {
							// String url = APIConstants.imageUpLoad;
							// new SyncUpLoadImageTask(context, url, list)
							// .execute();
							new AsyncBatchUpload(list, context).execute();
						} else {
							Toast.makeText(context, "网络已断开!",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(context, "请选择要上传的数据", Toast.LENGTH_SHORT)
								.show();
					}
				} else {
					Toast.makeText(context, "没有可以上传的数据", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});
		ivChecked.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				adapter.batch();
				if (btn_batch_upload.getVisibility() == View.GONE) {
					btn_batch_upload.setVisibility(View.VISIBLE);
				} else {
					btn_batch_upload.setVisibility(View.GONE);
				}
				adapter.notifyDataSetChanged();
			}
		});

		tv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AppManager.getAppManager().finishActivity();
			}
		});
		// listView.setOnItemClickListener(onItemClickListener);
		adapter = new UnUpLoadDataAdatper(upLoadDataList, context, this);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void click(View v) {
		pos = (Integer) v.getTag();
		u = upLoadDataList.get(pos);
		String by = u.getBZ();
		if (u.isUpLoad()) {
			new AlertDialog.Builder(context)
					.setTitle("删除")
					.setMessage("确定定删除" + u.getQYMC() + "的采集数据吗？")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									DBUtils.setUpLoaded(u.getQYMC(), context);
									// upLoadDataList = DBUtils
									// .getUnUpLoadData(context);
									// adapter.setList(upLoadDataList);
									adapter.getList().remove(pos);
									adapter.notifyDataSetChanged();
									dialog.dismiss();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}

							}).create().show();
		} else {
			upLoadTextData(u);
			// if ("0".equals(by)) {
			// String[] photos = u.getPhotos().split(",");
			// String url = APIConstants.imageUpLoad;
			// String username = u.getQYMC();
			// if (NetUtils.isConnected(context)) {
			// // new HttpMultipartPost(context, photos, url, this,
			// // username)
			// // .execute();
			// } else {
			// Toast.makeText(context, "网络已断开!", Toast.LENGTH_SHORT)
			// .show();
			// }
			// } else {
			// upLoadTextData(u);
			// }
			//
			// // new MyAsyncTask().execute(u);
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				upLoadTextData(u);
				break;
			case 3:
				String QYMC = (String) msg.obj;
				DBUtils.setUpLoaded(QYMC, context);
				upLoadDataList = DBUtils.getUnUpLoadData(context);
				adapter.setList(upLoadDataList);
				adapter.notifyDataSetChanged();
				break;
			}
		}

	};

	private void upLoadTextData(final UnUpLoad u) {
		String url = APIConstants.upload_api;
		AsyncHttpClient client = new AsyncHttpClient();
		client.setTimeout(1000 * 10);
		RequestParams params = new RequestParams();
		params.put("QYMC", u.getQYMC());
		params.put("X", u.getX());
		params.put("Y", u.getY());
		params.put("CJR", u.getCJR());
		params.put("CJSJ", u.getCJSJ());
		params.put("BZ", u.getBZ());
		params.put("JD", u.getStreet());// 街道
		params.put("SC", u.getCommunity());// 社区
		params.put("manualMode", u.getManualMode());// 坐标获取模式 0自动获取 1手动获取

		Log.d("tag", "数据上传：" + url + "   " + params.toString());
		client.post(url, params, new AsyncHttpResponseHandler() {

			@Override
			@Deprecated
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				Log.d("tag", "数据上传失败：" + content);
				pd.dismiss();
				Toast.makeText(context, "服务器异常", 1).show();
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				pd = ProgressDialog.show(context, "数据上传", "....正在上传数据....");
			}

			@Override
			@Deprecated
			public void onSuccess(int statusCode, Header[] headers,
					String content) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, content);

				Log.d("tag", "数据上传成功：" + content);
				pd.dismiss();
				JSONObject json = null;
				try {
					json = new JSONObject(content);
				} catch (JSONException e) {
					// TODO Auto-generated catch block

					e.printStackTrace();
					pd.dismiss();
					Toast.makeText(context, "数据上传失败", 1).show();
				}
				String result = json.optString("flag");
				if ("0".equals(result)) {
					Toast.makeText(context, "数据上传成功", 1).show();
					MyLog.i(TAG, "upload_success:" + u.toString());
					DBUtils.setUpLoaded(u.getQYMC(), context);
					upLoadDataList.remove(pos);
					adapter.notifyDataSetChanged();
				} else {
					MyLog.i(TAG, "upload_repeat:" + u.toString());
					upLoadDataList.get(pos).setUpLoad(true);
					adapter.notifyDataSetChanged();
					Toast.makeText(context, "数据上传重复,请酌情删除", Toast.LENGTH_SHORT)
							.show();
				}
			}

		});
	}

	@Override
	public void onPostExecute(String result) {
		// TODO Auto-generated method stub
		Log.d("tag", "图片上传结果回调：" + result);
		try {
			JSONObject json = new JSONObject(result);
			int res = json.optInt("flag");
			if (0 == res) {
				Toast.makeText(context, "图片上传成功", 1).show();
				Message msg = new Message();
				msg.what = ImageUpSuccess;
				handler.sendMessage(msg);
			} else {
				Toast.makeText(context, "图片上传失败", 1).show();
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Toast.makeText(context, "图片上传失败", 1).show();
			e.printStackTrace();
		}
	}

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			String flag = "";
			UnUpLoad u = upLoadDataList.get(arg2);
			if (!TextUtils.isEmpty(u.getPhotos())) {
				flag = "1";
			}

			Intent intent = new Intent(context, MainActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("UnUpLoad", u);
			bundle.putString("by", u.getBZ());
			bundle.putString("type", "UnUpLoad");
			bundle.putString("flag", flag);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		adapter.notifyDataSetChanged();
	}

	/**
	 * 批量上传数据的异步线程
	 * 
	 * @author Administrator
	 * 
	 */
	class SyncUpLoadImageTask extends AsyncTask<String, Integer, String> {
		private Context context;
		private ProgressDialog pd;
		private long totalSize;
		private String requestUrl;
		private List<UnUpLoad> list;

		public SyncUpLoadImageTask(Context context, String requestUrl,
				List<UnUpLoad> list) {
			this.context = context;
			this.requestUrl = requestUrl;
			this.list = list;

		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(context);
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pd.setMessage("...正在上传数据...");
			pd.setCancelable(false);
			pd.show();
		}

		@SuppressWarnings("deprecation")
		@Override
		protected String doInBackground(String... params) {
			String serverResponse = null;
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext httpContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(requestUrl);
			for (int x = 0; x < list.size(); x++) {
				if (list.get(x).isSelected()) {
					@SuppressWarnings("deprecation")
					// ContentBody cb = new StringBody(QYMC);
					String QYMC = list.get(x).getQYMC();
					String[] filePath = list.get(x).getPhotos().split(",");
					// pd.setMessage("...正在上传第" + (x + 1) + "条数据...");
					pd.setProgress(0);
					if (filePath.length >= 1) {
						if (!TextUtils.isEmpty(filePath[0])) {
							try {
								CustomMultipartEntity multipartContent = new CustomMultipartEntity(
										new ProgressListener() {
											@Override
											public void transferred(long num) {
												publishProgress((int) ((num / (float) totalSize) * 100));
											}
										});

								Business business = DBUtils.getBusiness(QYMC,
										context);
								String name = "";
								if (TextUtils.isEmpty(business
										.getBusiness_name())) {
									name = "_" + QYMC + "_";
								} else {
									name = business.getBusiness_type() + "_"
											+ business.getBusiness_name() + "_"
											+ business.getLicense_key();
								}

								ContentBody cb = new StringBody(name,
										Charset.forName("UTF-8"));
								// 上传企业名称
								multipartContent.addPart("username", cb);

								// 使用FileBody上传图片
								for (int i = 0; i < filePath.length; i++) {

									multipartContent
											.addPart("file" + i, new FileBody(
													new File(filePath[i])));
								}
								totalSize = multipartContent.getContentLength();
								// 上传
								httpPost.setEntity(multipartContent);
								HttpResponse response = httpClient.execute(
										httpPost, httpContext);
								serverResponse = EntityUtils.toString(response
										.getEntity());
								System.out.println(serverResponse);

								try {
									JSONObject json = new JSONObject(
											serverResponse);
									int res = json.optInt("flag");
									if (0 == res) {
										upLoadData(list.get(x), x);
									} else {
										pd.dismiss();
										runOnUiThread(new Runnable() {

											@Override
											public void run() {
												// TODO Auto-generated method
												// stub
												Toast.makeText(context,
														"数据上传失败",
														Toast.LENGTH_LONG)
														.show();
											}
										});
										return "-1";
									}

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									pd.dismiss();
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(context, "数据上传失败",
													Toast.LENGTH_LONG).show();
										}
									});
									return "-1";
								}
							} catch (Exception e) {
								pd.dismiss();
								runOnUiThread(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										Toast.makeText(context,
												"数据上传失败,网络或者服务器异常!",
												Toast.LENGTH_LONG).show();
									}
								});

								e.printStackTrace();
								return "-1";
							}
						} else {

							upLoadData(list.get(x), x);
						}
					} else {
						upLoadData(list.get(x), x);
					}
				}
			}
			pd.dismiss();
			return "0";

		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			pd.setProgress((int) (progress[0]));
		}

		@Override
		protected void onPostExecute(String result) {

			if ("0".equals(result)) {
				adapter.batch();
				btn_batch_upload.setVisibility(View.GONE);
				adapter.notifyDataSetChanged();
				ivChecked.setClickable(false);
			} else if ("-1".equals(result)) {

			} else if ("1".equals(result)) {

			}
			pd.dismiss();
		}

		@Override
		protected void onCancelled() {
			System.out.println("cancle");
		}

	}

	class AsyncBatchUpload extends AsyncTask<String, Integer, Integer> {
		private List<UnUpLoad> uploadList;
		private final int UPLOAD_SUCCESS = 0x30;
		private final int UPLOAD_FAIL = 0X31;
		private Context context;
		private ProgressDialog pd;

		public AsyncBatchUpload(List<UnUpLoad> uploadList, Context context) {
			super();
			this.uploadList = uploadList;
			this.context = context;
			this.pd = new ProgressDialog(context);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd.setTitle("数据上传");
			pd.setMessage("数据上传中...");
			pd.setCancelable(false);
			pd.show();
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (pd.isShowing()) {
				pd.dismiss();
			}
			switch (result) {
			case UPLOAD_FAIL:
				Toast.makeText(context, "上传数据出现异常", Toast.LENGTH_LONG).show();
				break;
			case UPLOAD_SUCCESS:
				adapter.batch();
				btn_batch_upload.setVisibility(View.GONE);
				adapter.notifyDataSetChanged();
				ivChecked.setClickable(false);
				Toast.makeText(context, "上传数据成功,重复的数据请酌情处理。", Toast.LENGTH_LONG)
						.show();
				break;

			default:
				break;
			}

		}

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			if (null != uploadList && uploadList.size() > 0) {
				for (int i = 0; i < uploadList.size(); i++) {
					if (uploadList.get(i).isSelected()) {
						String result = upLoadData(uploadList.get(i), i);
						if (TextUtils.isEmpty(result)) {
							return UPLOAD_FAIL;
						}
					}
				}
			}

			return UPLOAD_SUCCESS;
		}

	}

	private String upLoadData(final UnUpLoad u, final int position) {
		String urlstr = APIConstants.upload_api_;
		String result = "";
		try {
			URL url = new URL(urlstr);
			HttpURLConnection uRLConnection = (HttpURLConnection) url
					.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("GET");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			uRLConnection.connect();

			DataOutputStream out = new DataOutputStream(
					uRLConnection.getOutputStream());

			String content = "QYMC=" + ToURLEncode.toURLEncoded(u.getQYMC())
					+ "&X=" + ToURLEncode.toURLEncoded(u.getX()) + "&Y="
					+ ToURLEncode.toURLEncoded(u.getY()) + "&CJR="
					+ ToURLEncode.toURLEncoded(u.getCJR()) + "&CJSJ="
					+ ToURLEncode.toURLEncoded(u.getCJSJ()) + "&BZ="
					+ ToURLEncode.toURLEncoded(u.getBZ()) + "&JD="
					+ ToURLEncode.toURLEncoded(u.getStreet()) + "&SC="
					+ ToURLEncode.toURLEncoded(u.getCommunity())
					+ "&manualMode="
					+ ToURLEncode.toURLEncoded(u.getManualMode());
			out.writeBytes(content);
			out.flush();
			out.close();

			InputStream is = uRLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String response = "";
			String readLine = null;
			while ((readLine = br.readLine()) != null) {
				// response = br.readLine();
				response = response + readLine;
			}
			is.close();
			br.close();
			uRLConnection.disconnect();
			Log.d("tag", "数据上传成功：" + response);
			JSONObject json = null;
			try {
				json = new JSONObject(response);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Toast.makeText(context, "数据上传失败", 1).show();
					}
				});
			}
			result = json.optString("flag");
			if ("0".equals(result)) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						MyLog.i(TAG, "upload_repeat:" + u.toString());
						// TODO Auto-generated method stub
						// Toast.makeText(context, "数据上传成功", 1).show();
					}
				});
				Message msg = new Message();
				msg.what = 3;
				msg.obj = u.getQYMC();
				handler.sendMessage(msg);
			} else {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						MyLog.i(TAG, "upload_repeat:" + u.toString());
						adapter.getList().get(position).setUpLoad(true);
						// Toast.makeText(context, "数据上传重复,请酌情删除",
						// Toast.LENGTH_SHORT).show();
					}
				});

			}

			return result;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			Log.e("upload", e.getMessage());
			result = "";
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("upload", e.getMessage());
			result = "";
			return result;
		}

	}

}
